package com.webrtc.demo.contacts

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.webrtc.demo.R
import com.webrtc.demo.call.RTCSignalClient
import com.webrtc.demo.util.ContactsUtils
import com.yzq.zxinglibrary.android.CaptureActivity
import com.yzq.zxinglibrary.common.Constant
import kotlinx.android.synthetic.main.activity_add_contacts.*
import pub.devrel.easypermissions.AfterPermissionGranted
import pub.devrel.easypermissions.EasyPermissions

class AddContactsActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks {

    companion object {

        private const val RC_CAMERA_AND_EXTERNAL_STORAGE = 1001
        private const val RC_SCAN = 1002

        fun launch(activity: Activity, requestCode: Int) {
            activity.startActivityForResult(
                Intent(activity, AddContactsActivity::class.java),
                requestCode
            )
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        title = "添加联系人"
        setContentView(R.layout.activity_add_contacts)

        scanIv.setOnClickListener { requiresPermissionsAfterScan() }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        val inflater = menuInflater
        inflater.inflate(R.menu.add_contacts_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.confirm -> {
                val name = nameEdt.text.toString()
                var nickname: String? = nicknameEdt.text.toString().trim()
                if (nickname!!.isEmpty()) {
                    nickname = null
                }
                when {
                    name.isBlank() -> {
                        Toast.makeText(this, "请输入名称", Toast.LENGTH_SHORT).show()
                    }
                    name == ContactsUtils.getMyUid(this) -> {
                        Toast.makeText(this, "不能添加自己为联系人", Toast.LENGTH_SHORT).show()
                    }
                    else -> {
                        RTCSignalClient.sendAddFriend(name) {
                            val result =
                                ContactsUtils.addContacts(this, name, nickname)
                            if (result) {
                                setResult(Activity.RESULT_OK)
                                finish()
                            } else {
                                Toast.makeText(this, "联系人已存在", Toast.LENGTH_SHORT).show()
                            }
                        }
                    }
                }
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    @AfterPermissionGranted(RC_CAMERA_AND_EXTERNAL_STORAGE)
    private fun requiresPermissionsAfterScan() {
        val perms = arrayOf(
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE
        )
        if (EasyPermissions.hasPermissions(this, *perms)) {
            val intent = Intent(this, CaptureActivity::class.java)
            startActivityForResult(intent, RC_SCAN)
        } else {
            EasyPermissions.requestPermissions(
                this,
                "Need permissions for camera & read external storage",
                RC_CAMERA_AND_EXTERNAL_STORAGE,
                *perms
            )
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == RC_SCAN && resultCode == Activity.RESULT_OK) {
            data?.let {
                val content = it.getStringExtra(Constant.CODED_CONTENT)
                nameEdt.setText(content)
            }
        }
    }

}